package com.lzb.browser.activity;

import android.os.Bundle;
import android.os.Handler;
import android.view.View;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.GridLayoutManager;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.enums.PopupPosition;
import com.lzb.browser.BaseAc;
import com.lzb.browser.Content;
import com.lzb.browser.R;
import com.lzb.browser.adapter.AlbumAdapter;
import com.lzb.browser.basic.utils.FileUtil;
import com.lzb.browser.basic.utils.RxUtil;
import com.lzb.browser.bean.AlbumBean;
import com.lzb.browser.databinding.ActivityPriPictureBinding;
import com.lzb.browser.dialog.AddAlbumDialog;
import com.lzb.browser.dialog.DeleteDialog;
import com.lzb.browser.dialog.EditDialog;
import com.lzb.browser.dialog.RenameDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.rxjava3.core.ObservableEmitter;

public class PriPictureActivity extends BaseAc<ActivityPriPictureBinding> implements View.OnClickListener, OnItemClickListener {

    private AlbumAdapter albumAdapter;
    private List<AlbumBean> listShow = new ArrayList<>();//全部数据
    private List<String> listSel = new ArrayList<>();
    private boolean isEdit;


    @Override
    protected int onCreate() {
        return R.layout.activity_pri_picture;
    }

    @Override
    protected void initView() {
        mDataBinding.ivPriPictureBack.setOnClickListener(view -> getOnBackPressedDispatcher().onBackPressed());

        mDataBinding.ivAdd.setOnClickListener(this);
        mDataBinding.tvCancel.setOnClickListener(this);
        mDataBinding.tvRename.setOnClickListener(this);
        mDataBinding.tvDelete.setOnClickListener(this);

        mDataBinding.rvAlbumList.setLayoutManager(new GridLayoutManager(mContext, 3));
        albumAdapter = new AlbumAdapter();
        mDataBinding.rvAlbumList.setAdapter(albumAdapter);
        albumAdapter.setOnItemClickListener(this);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.ivAdd) {//新建
            showEditDialog();
        } else if (id == R.id.tvCancel) {//取消
            isEdit = false;
            albumAdapter.setEdit(isEdit);
            listSel.clear();
            getData();
            mDataBinding.ivAdd.setVisibility(View.VISIBLE);
            mDataBinding.tvCancel.setVisibility(View.GONE);
            mDataBinding.llEdit.setVisibility(View.GONE);
        } else if (id == R.id.tvRename) {//重命名
            if (listSel.size() == 0) return;
            if (listSel.size() > 1) {
                ToastUtils.showShort(getString(R.string.just_sel_one_rename));
                return;
            }
            showRenameDialog();
        } else if (id == R.id.tvDelete) {//删除
            if (listSel.size() == 0) return;
            showDeleteDialog();
        }
    }

    @Override
    public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (isEdit) {
            if (position == 0) return;
            if (albumAdapter.getItem(position).isSelected()) {
                albumAdapter.getItem(position).setSelected(false);
                listSel.remove(albumAdapter.getItem(position).getPath());
            } else {
                albumAdapter.getItem(position).setSelected(true);
                listSel.add(albumAdapter.getItem(position).getPath());
            }
            albumAdapter.notifyItemChanged(position);
        } else {
            PictureAlbumActivity.sFilePath = FileUtils.getFileName(albumAdapter.getItem(position).getPath());
            startActivity(PictureAlbumActivity.class);
        }
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        getData();
    }

    private void getData() {
        listShow.clear();
        String defaultPath = PathUtils.getFilesPathExternalFirst() + Content.privacyPicture + "/" + getString(R.string.default_album);
        if (!FileUtils.isFileExists(defaultPath)) {
            FileUtils.createOrExistsDir(defaultPath);
        }
        String path = PathUtils.getFilesPathExternalFirst() + Content.privacyPicture;
        List<File> files = FileUtils.listFilesInDir(path);
        if (files.size() > 0) {
            for (File file : files) {
                listShow.add(new AlbumBean(file.getPath()));
            }
        }
        if (listShow.size() > 0) {
            albumAdapter.setList(listShow);
            mDataBinding.rvAlbumList.setVisibility(View.VISIBLE);
        } else {
            mDataBinding.rvAlbumList.setVisibility(View.GONE);
        }
    }

    private void showEditDialog() {
        EditDialog dialog = new EditDialog(mContext);
        BasePopupView basePopupView = new XPopup.Builder(mContext).popupPosition(PopupPosition.Bottom) //手动指定弹窗的位置
                .offsetX(0)//x轴偏移
                .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                .atView(mDataBinding.ivAdd).hasShadowBg(false) // 去掉半透明背景
                .asCustom(dialog);
        dialog.setListener(new EditDialog.Ilistener() {
            @Override
            public void clickAdd() {
                showAddDialog();
            }

            @Override
            public void clickManage() {
                isEdit = true;
                albumAdapter.setEdit(isEdit);
                mDataBinding.ivAdd.setVisibility(View.GONE);
                mDataBinding.tvCancel.setVisibility(View.VISIBLE);
                mDataBinding.llEdit.setVisibility(View.VISIBLE);
            }
        });
        basePopupView.show();
    }

    private void showAddDialog() {
        AddAlbumDialog dialog = new AddAlbumDialog(mContext);
        dialog.setListener(new AddAlbumDialog.Ilistener() {
            @Override
            public void clickAddAlbum(String name) {
                String path = PathUtils.getFilesPathExternalFirst() + Content.privacyPicture + "/" + name;
                if (FileUtils.isFileExists(path)) {
                    ToastUtils.showShort(getString(R.string.album_is_exist));
                } else {
                    FileUtils.createOrExistsDir(path);
                    ToastUtils.showShort(getString(R.string.add_album_suc));
                }
                getData();
            }
        });
        dialog.show();
    }

    private void showRenameDialog() {
        RenameDialog dialog = new RenameDialog(mContext);
        dialog.setListener(new RenameDialog.Ilistener() {
            @Override
            public void clickRename(String name) {
                boolean isOk = FileUtils.rename(listSel.get(0), name);
                if (isOk) {
                    ToastUtils.showShort(getString(R.string.rename_suc));
                } else {
                    ToastUtils.showShort(getString(R.string.album_is_exist));
                }
                getData();
            }
        });
        dialog.show();
    }

    private void showDeleteDialog() {
        DeleteDialog dialog = new DeleteDialog(mContext);
        dialog.setListener(new DeleteDialog.Ilistener() {
            @Override
            public void clickDelete() {
                delete();
            }
        });
        dialog.show();
    }

    //删除
    private void delete() {
        showDialog(getString(R.string.delete_ing));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<String>() {
                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        for (int i = 0; i < listSel.size(); i++) {
                            List<File> files = FileUtils.listFilesInDir(listSel.get(i));
                            if (files.size() > 0) {
                                for (File file : files) {
                                    String filePath = FileUtil.generateFilePath(Content.privacyPicture + "/" + getString(R.string.default_album), "." + FileUtils.getFileExtension(file.getPath()));
                                    FileUtils.copy(file.getPath(), filePath);
                                }
                            }
                            FileUtils.delete(listSel.get(i));
                        }
                        emitter.onNext("");
                    }

                    @Override
                    public void accept(String path) {
                        dismissDialog();
                        ToastUtils.showShort(getString(R.string.delete_suc));
                        listSel.clear();
                        getData();
                    }
                });
            }
        }, 500);
    }
}